package main

import (
	"encoding/gob"
	"fmt"
	"io"
	"os"
)

type Player struct {
	Name   string
	Age    int
	Gender string
}

func directWriteADTToFile(path string, players []Player) error {
	f, err := os.Create(path)
	if err != nil {
		fmt.Println("open file failed:", err)
		return err
	}
	defer func() {
		f.Sync()
		f.Close()
	}()
	enc := gob.NewEncoder(f)

	for _, player := range players {
		err = enc.Encode(player)
		if err != nil {
			return err
		}

	}
	return nil
}

func directReadADTFromFile(path string) error {
	f, err := os.Open(path)
	if err != nil {
		fmt.Println("open file failed:", err)
		return err
	}
	defer f.Close()
	dec := gob.NewDecoder(f)
	var player Player
	for {
		err := dec.Decode(&player)
		if err == io.EOF {
			fmt.Println("meet file EOF")
			return nil
		}
		if err != nil {
			fmt.Println("read file failed:", err)
			return err
		}
		fmt.Printf("%v\n", player)
	}
}

func main() {
	var players = []Player{
		{"zzz", 18, "male"},
		{"yyy", 1, "female"},
		{"lll", 118, "male"},
	}
	path := "1.txt"
	err := directWriteADTToFile(path, players)
	if err != nil {
		fmt.Println("write to file failed:", err)
		return
	}
	err = directReadADTFromFile(path)
	if err != nil {
		fmt.Println("read file failed:", err)
		return
	}

}
